package com.hspedu.furns.filter;

import com.hspedu.furns.entity.Member;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author 徐
 * @version 1.0
 * 管理员独立出来一个过滤器
 * 用于权限验证的过滤器，对指定的url进行验证
 * 即，如果登陆过就放行，没有就去登陆
 */
public class ManageFilter implements Filter {

    //用于存放 指定的 不过滤的 url
    private List<String> excludedUrls;

    /**
     * 读取到配置文件中的排除url
     * @param filterConfig
     * @throws ServletException
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        //获取到 param-value
        String strExcludedUrls = filterConfig.getInitParameter("excludedUrls");
        //分割，放入数组
        String[] splitUrl = strExcludedUrls.split(",");
        //将 splitUrl 转成 List
        // Arrays.asList(splitUrl) 会转成 List<String>
        excludedUrls = Arrays.asList(splitUrl);
    }

    /**
     * webxml里面拦截url /* 拦截所有
     * 会导致member对象一定为null,而且css，js,图片也不能引入
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        //得到请求的url
        //1.把 servletRequest 转成 request
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //2.得到请求的url
        String url = request.getServletPath();
        System.out.println("url2=" + url);

        //6.判断是否进行过滤，即判断集合中的url
        if (!excludedUrls.contains(url)) {
            //3.得到request域中的对象
            String manageUrl = (String) request.getSession().getAttribute("manageUrl");
            //4.判断manageUrl是否为null,即验证是否登陆
            if (manageUrl == null || manageUrl.equals("")) {
                //转发到登录页面,请求转发不走过滤器
                request.getRequestDispatcher("/views/manage/manage_login.jsp")
                        .forward(servletRequest, servletResponse);
                return;
            }
        }
        //5.member不为null,登录过，放行
        //7.判断 不需要 进行过滤,放行
        filterChain.doFilter(servletRequest, servletResponse);


    }

    public void destroy() {

    }

}
